<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"/> 首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>类别列表</el-breadcrumb-item>
      <!-- 使用v-for指令遍历history数组中的每个item，并为每个item生成一个el-breadcrumb-item组件 -->
      <!-- 将当前元素的name属性作为该面包屑项的唯一标识（key）。 -->
      <el-breadcrumb-item v-for="item in history" :key="item.name">
        <!-- 使用v-text指令将item.name的值显示在span标签中 -->
        <span v-text="item.name"></span>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider/>

    <el-table :data="tableData" border style="width: 100%">
      <!--至少有一列设置宽度-->
      <el-table-column prop="id" label="ID" width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" width="300" header-align="center"></el-table-column>
      <el-table-column prop="keywords" label="关键词列表" header-align="center"></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column label="是否启用" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enable"
              @change="togglesEnable(scope.row)"
              :disabled="scope.row.isParent===1"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="显示在导航栏" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.isDisplay"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="子级类别" width="100" align="center">
        <template slot-scope="scope">
<!--          scope.row是获取当前列的数据-->
          <el-button size="small" @click="showSubCategoryList(scope.row)" :disabled="scope.row.isParent===0">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <!--添加绑定事件-->
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="small"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="small"
                     @click="openDeleteDialog(scope.row)" :disabled="scope.row.isParent===1"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:10px;">
      <el-button style="float: right" @click="goBack" v-if="this.history.length">返回</el-button>
    </div>

    <el-dialog title="修改类别详情" :visible.sync="dialogFormVisible">
      <el-form :model="editForm">
        <el-form-item label="相册名称" :label-width="formLabelWidth">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="相册简介" :label-width="formLabelWidth">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" :label-width="formLabelWidth">
          <el-input v-model="editForm.sort"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEidtForm()">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      history: [],// 记录点击"查看子级"是的历史记录,便于后续返回
      currentParentId: 0,
      tableData: [],
      dialogFormVisible: false,
      editForm: {
        id: '',
        name: '',
        description: '',
        sort: ''
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    /**
     * 返回上一级操作，更新当前父类别ID为上一级类别的ID，删除历史记录中的最后一个元素，加载类别列表数据
     */
    goBack() {
      let parentCategory = this.history[this.history.length - 1];
      // 取出对应的最后一个元素
      this.currentParentId = parentCategory.parentId;
      // 删除数组中的最后一个元素
      this.history.pop();
      this.loadCategoryList();
    },

    /**
     * 显示子类别列表，更新历史记录中对应深度的类别信息，更新当前父类别ID，加载类别列表数据
     *
     * @param {Object} category - 类别对象
     */
    showSubCategoryList(category) {
      this.history[category.depth - 1] = category;
      this.currentParentId = category.id;
      this.loadCategoryList()
    },

    /**
     * 启用/禁用类别
     *
     * @param {Object} category - 类别对象
     */
    togglesEnable(category){
      let url='http://localhost:9080/categories/'+category.id+'/';
      let enableText = ['禁用','启用'];
      if (category.enable===1){
        url += 'enable';
      }else {
        url += 'disable';
      }
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response)=>{
        let responseBody = response.data;
        if (responseBody.state===2000){
          let message = '操作成功,已将['+category.name+']的状态改为['+enableText[category.enable]+']!';
          this.$message({
            message: message,
            type: 'success'
          })
        }else if (responseBody.state===4040){
          this.$message.error(responseBody.message);
          this.loadCategoryList();
        }
      })
    },

    /**
     * 打开编辑对话框，根据相册ID获取数据并显示编辑表单
     *
     * @param {Object} album - 相册对象
     */
    openEditDialog(album) {
      console.log("尝试打开编辑[id=" + album.id + "]数据的对话框.....");
      let url = 'http://localhost:9080/albums/' + album.id;
      console.log('url' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state === 2000) {
          this.editForm = responseBody.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              console.log(action)
              this.loadCategoryList();
            }
          });
        }
      })
    },

    /**
     * 提交编辑表单，更新相册数据
     */
    submitEidtForm() {
      let url = 'http://localhost:9080/albums/' + this.editForm.id + '/update';
      console.log('url = ' + url);
      let formData = this.qs.stringify(this.editForm);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state === 2000) {
          this.dialogFormVisible = false;
          this.$message({
            message: '修改相册成功!',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (responseBody.state === 4040) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              console.log(action)
              this.loadCategoryList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      })
    },

    /**
     * 打开删除确认框，确认删除相册操作
     *
     * @param {Object} album - 相册对象
     */
    openDeleteDialog(album) {
      console.log("尝试打开删除[id=" + album.id + "]数据的确认框.....")
      this.$confirm('此操作将永久删除[' + album.name + ']相册, 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(album);
      }).catch(() => {
      });
    },

    /**
     * 处理删除相册操作
     *
     * @param {Object} album - 相册对象
     */
    handleDelete(album) {
      let url = 'http://localhost:9080/albums/' + album.id + '/delete';
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseData = response.data;
        // 根据responseData中的状态码进行不同的处理
        if (responseData.state === 2000) {
          // 如果状态码为2000，调用loadCategoryList方法，并显示成功消息
          this.loadCategoryList();
          this.$message.success('删除成功!')
        } else if (responseData.state === 4040) {
          // 如果状态码为4040，弹出警告框显示responseData中的消息，并在确认后调用loadCategoryList方法
          this.$alert(responseData.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              console.log(action)
              this.loadCategoryList();
            }
          });
        } else {
          // 其他状态码，显示错误消息
          this.$message.error(responseData.message)
        }
      })
    },

    /**
     * 加载类别列表数据
     */
    loadCategoryList() {
      // 定义后端接口
      let url = 'http://localhost:9080/categories/list-by-parent?parentId=' + this.currentParentId;
      // 在控制台打印url的数值
      console.log("url=" + url);
      // 使用axios发送GET请求到url，并在获取响应后执行then方法
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        // 从响应中获取数据赋值给responseData变量
        let responseData = response.data;
        // 如果responseData中的state属性值等于2000
        if (responseData.state === 2000) {
          // 将responseData中的data属性值赋给this.tableData
          this.tableData = responseData.data;
        }
      })
    }
  },
  // 生命周期方法
  mounted() {
    this.loadCategoryList();
  }
}
</script>